package com.topscomm.pm.script;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.pm.PmScript;
import com.topscomm.pm.pojo.PmReceiptApplyEntity;
import com.topscomm.pm.quartz.PmTaskLogSupplementApplyJob;
import com.topscomm.pm.service.impl.PmReceiptApplyService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.ParameterCache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class PmReceiptScript extends PmScript {

    public final static Logger logger = LoggerFactory.getLogger(PmReceiptScript.class);
    /**
     * @author: wushenghong
     * @date: 2020/6/4
     * @description: 项目收据金额更新
     */
    @Transactional
    public void updateReceiptMoneyToProject(ITapService service, TapEntity entity) throws Exception {
        // 审批节点实例11
        CboApprovalNodeInsEntity nodeIns = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeIns.getSourceid());
        PmReceiptApplyService pmReceiptApplyService = (PmReceiptApplyService) SpringUtil.getBean("pmReceiptApplyService");
        pmReceiptApplyService.updateReceiptMoneyOfProjectBase(sourceId, true);
//        pmReceiptApplyService.updateReceiptReturnMoney(sourceId, true);
        // 作废申请
        PmReceiptApplyEntity pmReceiptApplyEntity = pmReceiptApplyService.queryById(sourceId);
        if (pmReceiptApplyEntity != null) {
            if (!("1".equals(pmReceiptApplyEntity.getCategory()))) {
                Long oldId = pmReceiptApplyEntity.getOldid();
                Map<String, Object> updateParam = new HashedMap<>();
                updateParam.put("id", oldId);
                updateParam.put("iscancel", '1');
                updateParam.put("returnmoney", 0);//回款金额置为0
                pmReceiptApplyService.update(updateParam);
            }
        }
    }

    /**
     * @author: wudaliang
     * @date: 2021-07-27
     * @description: 对接发票管理平台和物流系统
     * @return: void
     * @modify:
     */
    @Transactional
    public void dockSystem(ITapService service, TapEntity entity){
        //审批节点实例
        CboApprovalNodeInsEntity nodeIns = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeIns.getSourceid());
        PmReceiptApplyService pmReceiptApplyService = (PmReceiptApplyService) SpringUtil.getBean("pmReceiptApplyService");
        PmReceiptApplyEntity pmReceiptApplyEntity = pmReceiptApplyService.queryById(sourceId);
        if(pmReceiptApplyEntity!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("sourceDocNo",pmReceiptApplyEntity.getDocno()); //来源单号
            map.put("sourceSystem","PM"); //来源系统
            map.put("sourceModule","Receipt"); //来源模块
            map.put("sourceModuleDocType","Receipt"); //来源模块单据类型
            map.put("userName",pmReceiptApplyEntity.getUsername()); //来源申请人姓名
            map.put("userCode",pmReceiptApplyEntity.getUsercode()); //来源申请人工号
            map.put("deptCode",pmReceiptApplyEntity.getReceiptdeptcode()); //来源申请部门编码
            map.put("deptName",pmReceiptApplyEntity.getReceiptdeptname()); //来源申请部门名称
            map.put("orgCode",pmReceiptApplyEntity.getReceiptorgcode());  //  todo：收据开具公司编码
            map.put("orgName",pmReceiptApplyEntity.getReceiptorgname()); //收据开具公司名称
            map.put("dateOption",pmReceiptApplyEntity.getReceiptdatetype()); //收据开具日期类别
            map.put("totalPayMoney",pmReceiptApplyEntity.getReceiptmoney()); //收据金额
            map.put("payCustomerName",pmReceiptApplyEntity.getCustomername());//客户名称
            map.put("sendType",pmReceiptApplyEntity.getReceivertype()); //收件人性质
            map.put("receivePerson",pmReceiptApplyEntity.getReceiver()); //收件人
            map.put("receivePhone",pmReceiptApplyEntity.getReceivertel());//收件人手机号
            map.put("receiveTel",pmReceiptApplyEntity.getReceiverfixedtel()); //收件人固话号
            map.put("sendAddress",pmReceiptApplyEntity.getMailaddress()); //邮寄地址
            map.put("realDate",pmReceiptApplyEntity.getActualreceiptdate());  //收据真实开具日期
            map.put("receiptBillNo",pmReceiptApplyEntity.getReceiptcode()); //收据号
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(2000);// 设置超时
            requestFactory.setReadTimeout(10000);// 读取超时时间
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(map, headers);
            // 对接开票平台
            String url = ParameterCache.getValue("BillDataSys");
            String billDataSysAppKey = ParameterCache.getValue("BillDataSysAppKey");
            url=url+"?appkey="+billDataSysAppKey;
            try {
                ResponseEntity<JSONObject> response = restTemplate
                    .postForEntity(url, request, JSONObject.class);
                // todo: 注意返回格式是否正确
                if(response.getBody().getBooleanValue("success")==false){
                    throw new MessageException(response.getBody().getString("message"));
                }
            } catch (RestClientException e) {
                e.printStackTrace();
                throw new MessageException("调用开票平台同步发票信息接口失败！");
            }

            String ismail = pmReceiptApplyEntity.getIsmail();
            // 需要邮寄的收据调用物流生成发货计划
            if(ismail!=null&&!ismail.isEmpty()&&"0".equals(ismail)){
                HashMap<String, Object> deliverymap = new HashMap<>();
                deliverymap.put("sourcesys", "pm"); //来源系统
                deliverymap.put("sourcemodule", "ReceiptBill"); //来源模块
                deliverymap.put("sourcedocno", pmReceiptApplyEntity.getDocno());//来源单号
                deliverymap.put("sourcemoduledoctype", "PmReceiptBill"); //来源模块单据类型
                deliverymap.put("companycode",pmReceiptApplyEntity.getReceiptorgcode()); //todo:发货属公司
                deliverymap.put("companyname", pmReceiptApplyEntity.getReceiptorgname()); // 发货属公司
                deliverymap.put("deptcode", pmReceiptApplyEntity.getReceiptdeptcode()); //发货部门
                deliverymap.put("deptname", pmReceiptApplyEntity.getReceiptdeptname());//发货部门
                deliverymap.put("usercode", pmReceiptApplyEntity.getUsercode()); //发货业务申请人
                deliverymap.put("username", pmReceiptApplyEntity.getUsername()); //发货业务申请人
                deliverymap.put("d_usercompany", pmReceiptApplyEntity.getCustomername());//到件方公司
                deliverymap.put("d_username", pmReceiptApplyEntity.getReceiver()); //到件联系人
                deliverymap.put("d_usertel", pmReceiptApplyEntity.getReceiverfixedtel()); //到件人固定电话
                deliverymap.put("d_usermobile", pmReceiptApplyEntity.getReceivertel()); //到件方手机
                deliverymap.put("d_useraddress", pmReceiptApplyEntity.getMailaddress()); //到件方详细地址
                deliverymap.put("express", pmReceiptApplyEntity.getCourier()); //快递类型
//                deliverymap.put("j_usercode", pmReceiptApplyEntity.getUsercode()); //指定寄件人工号
//                deliverymap.put("j_username", pmReceiptApplyEntity.getUsername()); //指定寄件人名称
                List<Map> deliverylineList = new ArrayList<>();
                Map deliverylineMap=new HashMap();
                deliverylineMap.put("itemname", "收据"); //物品名称
                deliverylineMap.put("num", 1); //数量
                deliverylineList.add(deliverylineMap);
                deliverymap.put("listLine",deliverylineList);
                String deliveryurl = ParameterCache.getValue("DeliveryInfoSys");
                SimpleClientHttpRequestFactory deliveryrequestFactory = new SimpleClientHttpRequestFactory();
                deliveryrequestFactory.setConnectTimeout(2000);// 设置超时
                deliveryrequestFactory.setReadTimeout(10000);//读取超时时间
                RestTemplate deliveryRestTemplate = new RestTemplate(deliveryrequestFactory);
                HttpHeaders deliveryheaders = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<Map<String,Object>> deliveryrequest = new HttpEntity<>(deliverymap, deliveryheaders);
                try {
                    ResponseEntity<JSONObject> response = deliveryRestTemplate
                        .postForEntity(deliveryurl, deliveryrequest, JSONObject.class);
                    if(response.getBody().getBooleanValue("success")==false){
                        throw new MessageException(response.getBody().getString("message"));
                    }
                } catch (RestClientException e) {
                    e.printStackTrace();
                    throw new MessageException("调用物流信息化系统普通发货计划创建接口失败！");
                }
            }

        }

    }
}
